package manager

import (
	"BlazeRider-backend/config"
	"database/sql"
	"fmt"
	"sync"
)

// DouYinFailGiftRecordManager 管理礼物赠送记录
type DouYinFailGiftRecordManager struct {
	roomGiftRecords map[string]map[string][]DouYinFailGiftRecord
	storage         DouYinFailGiftRecordMysqlStorage
	mu              sync.Mutex
}

// DouYinFailGiftRecord 表示单个礼物的赠送记录
type DouYinFailGiftRecord struct {
	MsgId      string       `json:"msg_id"`
	LiveRoomId string       `json:"live_room_id"`
	PageNum    int          `json:"page_num"`
	Times      int          `json:"times"`
	UserId     string       `json:"user_id"`
	GiftId     string       `json:"gift_id"`
	Amount     int          `json:"amount"`
	Value      int          `json:"value"`
	TotalValue int          `json:"total_value"`
	CreateAt   sql.NullTime `json:"create_at"` // 使用 NullTime
	UpdateAt   sql.NullTime `json:"update_at"` // 使用 NullTime
}

// DouYinFailGiftRecordWithUserInfo 表示单个礼物的赠送记录与用户相关联的数据
type DouYinFailGiftRecordWithUserInfo struct {
	MsgId         string       `json:"msg_id"`
	LiveRoomId    string       `json:"live_room_id"`
	Times         int          `json:"times"`
	Track         int          `json:"track"`
	UserId        string       `json:"user_id"`
	GiftId        string       `json:"gift_id"`
	GiftName      string       `json:"gift_name"`
	Amount        int          `json:"amount"`
	Value         int          `json:"value"`
	TotalValue    int          `json:"total_value"`
	Score         int          `json:"score"`
	TotalScore    int          `json:"total_score"`
	GiftLevel     int          `json:"gift_level"`
	GiftUpgrading int          `json:"gift_upgrading"`
	UserName      string       `json:"user_name"`
	UserHeadImg   string       `json:"head_img"`
	UserLevel     int          `json:"level"`
	UserScore     int          `json:"score"`
	ExpireAt      sql.NullTime `json:"expire_at"`
	CreateAt      sql.NullTime `json:"create_at"` // 使用 NullTime
	UpdateAt      sql.NullTime `json:"update_at"` // 使用 NullTime
}

func NewDouYinFailDouYinFailGiftRecordManager() *DouYinFailGiftRecordManager {
	var storage *DouYinFailGiftRecordMysqlStorage
	var err error
	if config.Get().Database.Enabled {
		storage, err = NewDouYinFailGiftRecordMysqlStorage()
		if err != nil {
			return nil
		}

		return &DouYinFailGiftRecordManager{
			storage: *storage,
		}
	}
	return &DouYinFailGiftRecordManager{
		roomGiftRecords: make(map[string]map[string][]DouYinFailGiftRecord),
	}
}

// 查询本局最后一次该礼物信息
func (grm *DouYinFailGiftRecordManager) GetGiftRecordByMsgId(msgID string) (*DouYinFailGiftRecord, error) {
	if config.Get().Database.Enabled {
		giftRecordMysqlInfo, err := grm.storage.GetGiftRecordByMsgId(msgID)
		if err != nil {
			return nil, err
		}

		return &DouYinFailGiftRecord{
			MsgId:      giftRecordMysqlInfo.MsgId,
			LiveRoomId: giftRecordMysqlInfo.LiveRoomId,
			Times:      giftRecordMysqlInfo.Times,
			UserId:     giftRecordMysqlInfo.UserId,
			GiftId:     giftRecordMysqlInfo.GiftId,
			Amount:     giftRecordMysqlInfo.Amount,
			Value:      giftRecordMysqlInfo.OneValue,
			TotalValue: giftRecordMysqlInfo.TotalValue,
			CreateAt:   giftRecordMysqlInfo.CreateAt,
			UpdateAt:   giftRecordMysqlInfo.UpdateAt,
		}, nil // 返回 LiveRoomStatus 和 false
	}
	return nil, fmt.Errorf("GetGiftRecordByMsgId no mem logic")
}

// AddGiftRecords 批量增加礼物赠送记录（内存+数据库双模式）
func (grm *DouYinFailGiftRecordManager) AddGiftRecordsBatch(records []DouYinFailGiftRecord) error {
	// 数据库模式
	if config.Get().Database.Enabled {
		var mysqlRecords []DouYinFailGiftRecordMysqlInfo
		for _, info := range records {
			var mysqlRecord DouYinFailGiftRecordMysqlInfo
			mysqlRecord = DouYinFailGiftRecordMysqlInfo{
				MsgId:      info.MsgId,
				LiveRoomId: info.LiveRoomId,
				PageNum:    info.PageNum,
				Times:      info.Times,
				UserId:     info.UserId,
				GiftId:     info.GiftId,
				Amount:     info.Amount,
				OneValue:   info.Value,
				TotalValue: info.TotalValue,
			}
			mysqlRecords = append(mysqlRecords, mysqlRecord)
		}
		if err := grm.storage.AddGiftRecordsBatch(mysqlRecords); err != nil {
			return fmt.Errorf("批量插入数据库失败: %v", err)
		}
		return nil
	}

	// 内存模式
	grm.mu.Lock()
	defer grm.mu.Unlock()

	for _, record := range records {
		// 从记录中提取关键信息
		liveRoomID := record.LiveRoomId
		userID := record.UserId

		// 初始化直播间记录
		userRecords, exists := grm.roomGiftRecords[liveRoomID]
		if !exists {
			userRecords = make(map[string][]DouYinFailGiftRecord)
			grm.roomGiftRecords[liveRoomID] = userRecords
		}

		// 强制设置内存模式特定字段（保持与单条插入逻辑一致）
		newRecord := record
		newRecord.Amount = 1 // 内存模式固定为1

		// 追加记录
		userRecords[userID] = append(userRecords[userID], newRecord)
	}
	return nil
}

// 查询本局最后一次该礼物信息
func (grm *DouYinFailGiftRecordManager) GetLastPageNumAndCountByLiveRoomId(liveRoomID string) (*DouYinFailGiftMaxPageInfo, error) {
	if config.Get().Database.Enabled {
		giftRecordMysqlInfo, err := grm.storage.GetLastPageNumAndCountByLiveRoomId(liveRoomID)
		if err != nil {
			return nil, err
		}

		return &DouYinFailGiftMaxPageInfo{
			LiveRoomId: giftRecordMysqlInfo.LiveRoomId,
			MaxPageNum: giftRecordMysqlInfo.MaxPageNum,
			Count:      giftRecordMysqlInfo.Count,
		}, nil // 返回 live room 的最大页数和对应数字
	}
	return nil, fmt.Errorf("GetLastGiftRecordByUserIdAndGiftId no mem logic")
}

// 查询本局最后一次该礼物信息
func (grm *DouYinFailGiftRecordManager) FilterExistingMsgIds(liveRoomIDs []string) ([]string, error) {
	if config.Get().Database.Enabled {
		existingIDs, err := grm.storage.FilterExistingMsgIds(liveRoomIDs)
		if err != nil {
			return nil, err
		}

		return existingIDs, nil // 返回 live room 的最大页数和对应数字
	}
	return nil, fmt.Errorf("FilterExistingMsgIds no mem logic")
}

// 查询本局最后一次该礼物信息
func (grm *DouYinFailGiftRecordManager) SetFailGiftDoneOrFail(msgId string, status, reason string) error {
	if config.Get().Database.Enabled {
		err := grm.storage.SetFailGiftDoneOrFail(msgId, status, reason)
		if err != nil {
			return err
		}

		return nil
	}
	return fmt.Errorf("SetFailGiftDoneOrFail no mem logic")
}
